<template>
  <div class="createPost-container">
    <el-form v-if="!infoLoading" ref="postForm" :model="postForm" :rules="rules" class="form-container" label-width="100px">
      <div class="createPost-main-container">
        <el-form-item v-if="!readOnly" label="链接地址" prop="username">
          <el-input v-model.trim="postForm.url" style="width:300px" />
        </el-form-item>
        <el-form-item v-if="!readOnly" label="图片" style="clear:both">
          <el-upload
            class="avatar-uploader"
            :action="this.$http.defaults.baseURL+'api/mpfile/upload/'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="myHeaders"
            accept="image/jpeg,image/png,image/gif"
          >
            <img v-if="imageUrl" :src="this.$http.defaults.baseURL+'api/mpfile/download?id='+parseInt(imageUrl)" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item v-else label="图片" style="clear:both">
          <a v-if="imageUrl" :href="this.$http.defaults.baseURL+'api/mpfile/download?id='+parseInt(imageUrl)" target="_blank"><img :src="this.$http.defaults.baseURL+'api/gen/file/download?id='+parseInt(imageUrl)" class="avatar"></a>
        </el-form-item>
        <el-form-item v-if="!readOnly" style="margin-bottom: 30px;">
          <el-button type="primary" :loading="loading" @click="submitForm">提交</el-button>
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>

const defaultForm = {
  url: '',
  usertype: '',
  userEnabled: true,
  id: null
}

export default {
  name: 'ArticleDetail',
  props: {
    readOnly: {
      type: Boolean,
      default: false
    },
    infoid: {
      type: Number,
      default: null
    },
    timestamp: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      imageUrl: '',
      infoLoading: false,
      postForm: Object.assign({}, defaultForm),
      loading: false,
      classOption: [],
      rules: {
      },
      tempRoute: {},
      myHeaders: {}
    }
  },
  watch: {
    timestamp: {
      handler(val, oldVal) {
        console.log('timestamp:' + val)
        this.getData(this.infoid)
      },
      immediate: true
    }
  },
  mounted() {
    this.myHeaders = {
      Authorization: 'Bearer ' + localStorage.getItem('token')
    }
  },
  created() {
    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isGIF = file.type === 'image/gif'
      const isLt20M = file.size / 1024 / 1024 < 20

      if (!isJPG && !isPNG && !isGIF) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!')
        return false
      }
      if (!isLt20M) {
        this.$message.error('上传图片大小不能超过 20MB!')
        return false
      }
    },
    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      console.log('test')
      if (res.success) {
        this.$message({
          message: '上传成功！',
          type: 'success'
        })
        this.imageUrl = res.result[0].id
        // this.fileList = []
        // this.files = []
      } else {
        this.$message({
          message: '上传失败:' + res.message,
          type: 'error'
        })
      }
    },
    getData(id) {
      this.infoLoading = true
      if (id) {
        this.$http
          .get('/api/busAdvert/getById?id=' + id)
          .then(response => {
            this.infoLoading = false
            if (response.data.success === true) {
              this.postForm = response.data.result
              this.imageUrl = response.data.result.fileId
            } else {
              console.log('获取失败:' + response.data.message)
              this.$message({
                message: '获取失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            console.log(error)
            this.infoLoading = false
          })
      } else {
        this.$nextTick(() => {
          this.infoLoading = false
        })
        this.postForm = Object.assign({}, defaultForm)
        this.imageUrl = ''
      }
    },
    submitForm() {
      console.log(this.postForm)
      this.$refs.postForm.validate(valid => {
        if (valid) {
          if (!this.imageUrl) {
            this.$message({
              message: '请上传图片',
              type: 'error'
            })
            return false
          }
          const para = {
            fileId: this.imageUrl,
            status: 1,
            type: 1,
            url: this.postForm.url,
            id: this.postForm.id ? this.postForm.id : null
          }
          this.loading = true
          this.$http
            .post('/api/busAdvert/save', para)
            .then(response => {
              this.loading = false
              if (response.data.success === true) {
                this.$message({
                  message: '提交成功',
                  type: 'success'
                })
                this.postForm = Object.assign({}, defaultForm)
                this.$emit('dialogHide')
              } else {
                console.log('提交失败:' + response.data.message)
                this.$message({
                  message: '提交失败:' + response.data.message,
                  type: 'error'
                })
              }
            })
            .catch((error) => {
              console.log(error)
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    // padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
